package com.vogue.api.common.rsa.advice;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

/**
 * 请求参数解密
 */
public class DecryptHttpInputMessage implements HttpInputMessage{

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private HttpHeaders headers;
    private InputStream body;


    public DecryptHttpInputMessage(HttpInputMessage inputMessage, String privateKey, boolean showLog) throws Exception {

        if (StringUtils.isEmpty(privateKey)) {
            throw new IllegalArgumentException("请配置privateKey秘钥 rsa.encrypt.privateKey");
        }

        this.headers = inputMessage.getHeaders();

        RSA rsa = new RSA(privateKey,null);

        String desKey = rsa.decryptStr(this.headers.get("desKey").get(0).toString(), KeyType.PrivateKey);
        log.info("动态desKey 解密后 :{}", desKey);

        String content = new BufferedReader(new InputStreamReader(inputMessage.getBody())).lines().collect(Collectors.joining(System.lineSeparator()));

        String decryptBody;

        if (JSONUtil.isJson(content)) {
            log.info("未加密未解密 :{}", content);
            decryptBody = content;
        } else {
            AES aes = new AES(Mode.ECB, Padding.PKCS5Padding, desKey.getBytes());
            decryptBody = aes.decryptStr(content);
            if(showLog) {
                log.info("解密前：{},解密后：{}", content, decryptBody);
            }
        }

        this.body = new ByteArrayInputStream(decryptBody.getBytes());
    }

    @Override
    public InputStream getBody(){
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }
}
